import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Timer;
import java.util.Vector;

import enigma.console.Console;
import enigma.core.Enigma;

public class RadioServer 
{
	private Console console = Enigma.getConsole("Server Window");
	private Timer timer = new Timer();
	byte[] receiveData = new byte[70];
	long delay = 5000;
	long sampleRate = 1000;
	String[] requests = {"1","2"};
	private void println(Object str){
		console.getOutputStream().println(str);
	}
	public RadioServer() throws Exception
	{
		System.out.println("Initialising Server");

		DatagramSocket welcomeSocket = new DatagramSocket(8000);
		HashMap<String,Radio> connections = new HashMap<String, Radio>();
		while(true){
			DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
			println("Waiting for connection ...");
			// Recieve packet
			welcomeSocket.receive(receivePacket);
			// get packet info
			int port = receivePacket.getPort();
			InetAddress ia = receivePacket.getAddress();
			
			
		
			RadioPacket p = new RadioPacket(receivePacket.getData());
			println(p.getPacketType());
			//String data = new String(receivePacket.getData());
			//String header = data.substring(0,11).trim();
			if(p.getPacketType().equals("STA")){  // 101 START
				String connectionName = ia+":"+port;
				
				println("New Connection created: "+ia+":"+port);
				Radio rad = new Radio(welcomeSocket, ia, port); 
				
				timer.scheduleAtFixedRate(rad,100,sampleRate);
				// add to connection pool
				if(!connections.containsKey(connectionName)) 
					connections.put(connectionName, rad);
				RadioPacket reply = new RadioPacket(100);
				reply.setPacketType("CON".getBytes());
				reply.setDataDelay((""+delay).getBytes());
				reply.setDataSampleRate((""+sampleRate).getBytes());
				byte[] sendData = reply.getBytes();
				DatagramPacket datagramPacket = new DatagramPacket(sendData, sendData.length, ia, port);
				welcomeSocket.send(datagramPacket);
	
			} else if(p.getPacketType().equals("STO")){  // 102 STOP
				String connectionName = ia+":"+port;
				// Remove radio from timer
				if(connections.containsKey(connectionName)){
					// Get the radio instance
					Radio rad = connections.get(connectionName);
					// Cancel it
					rad.cancel();
					// Remove it from pool
					connections.remove(connectionName);
				}
					
			}
		}
	}
	
	
	public static void main(String[] args) throws Exception{
		RadioServer radio = new RadioServer();
		
	}
}